<?php
/**
 * Created by PhpStorm.
 * User: asus
 * Date: 2018/5/25
 * Time: 2:15
 */

namespace app\common;


use app\common\model\User;

class Auth
{

    static public $instance = null;
    private $userData = [];

    private function __construct()
    {
    }

    static public function instance(){
        if(self::$instance == null){
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * @param $username
     * @param $password
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login($username, $password){
        $password = md5($password);
        $data = model("user")->where(["username"=>$username,"password"=>$password])->find();
        if(!$data){
            return false;
        }
        session("login",true);
        session("username",$data["username"]);
        session("password",$data["password"]);
        $this->userData = $data;
        return true;
    }

    /**
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get(){
        if(!$this->userData){
            $username = session("username");
            $password = session("password");
           if(session("login")){
               $data = model("user")->where(["username"=>$username,"password"=>$password])->find();
                if(!$data){
                    return false;
                }
                $this->userData = $data;
           }
        }
        return $this->userData;
    }

}